﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.SearchCriteria;

namespace NTQOnlineExam.Services.DBCommand.Examination
{
    public class SearchExamByCriteriaDbCommand : ICommand<SearchResult<ExaminationDTO>>
    {
        private readonly SearchCriteria.SearchCriteria _criteria;
        private readonly int _pageSize;
        private readonly int _pageIndex;
        private readonly int _userId;
        private const string _sql = @"
                 WITH PAGING AS (
                    SELECT ExaminationId,UserId, t.TermId, t.TermName,Score,CreateDate, row_number() over (order by {0}) as rownumber
                   FROM Examination e INNER JOIN Term t ON e.TermId = t.TermId {1}
                )
        ";

        public SearchExamByCriteriaDbCommand(SearchCriteria.SearchCriteria criteria, int userId, int pageSize, int pageIndex)
        {
            _criteria = criteria;
            _pageSize = pageSize;
            _pageIndex = pageIndex;
            _userId = userId;
        }

        public SearchResult<ExaminationDTO> Execute()
        {
            var connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            using (var connection = new SqlConnection(connectionString))
            {
                IList<ExaminationDTO> items = new List<ExaminationDTO>();
                int totalCount = 0;
                var cmd = new SqlCommand(BuildQuery(), connection);
                cmd.Parameters.Add("@PageIndex", SqlDbType.Int).Value = _pageIndex;
                cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = _pageSize;
                if (!string.IsNullOrWhiteSpace(_criteria.Keyword)) cmd.Parameters.Add("@Keyword", SqlDbType.NVarChar).Value = _criteria.Keyword;
                cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = _userId;
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                try
                {
                    if (!reader.Read()) return null;
                    totalCount = reader.GetInt32(0);
                    reader.NextResult();

                    while (reader.Read())
                    {
                        items.Add(GetDto(reader));
                    }
                }
                finally
                {
                    reader.Close();
                }
                return new SearchResult<ExaminationDTO>(items, totalCount);
            }
        }

        private ExaminationDTO GetDto(SqlDataReader reader)
        {
            return new ExaminationDTO
            {
                ExaminationId = (int)reader["ExaminationId"],
                CreateDate = Convert.ToDateTime(reader["CreateDate"]).ToString("dd-MM-yyyy HH:mm:ss"),
                TermName = reader["TermName"].ToString(),
                Score = (int)reader["Score"],
                UserId = (int)reader["UserId"],
                TermId = (int)reader["TermId"]
            };
        }


        private string BuildQuery()
        {
            var query = new StringBuilder();
            var sqlQuery = string.Format(_sql, BuildOrderClause(), BuildWhereClause());
            query.AppendFormat("{0} {1};{0} {2}", sqlQuery, @"SELECT COUNT(1) FROM paging", @" SELECT * FROM paging WHERE (@PageSize=0 or rownumber between @PageSize*@PageIndex+1 and @PageSize*(@PageIndex+1)) ORDER BY rownumber");
            return query.ToString();
        }

        private string BuildWhereClause()
        {
            var whereClause = " WHERE e.UserId = @UserId";
            if (!string.IsNullOrEmpty(_criteria.Keyword))
            {
                whereClause += " AND ( t.TermName LIKE '%'+@Keyword+'%' OR CAST(t.TermId AS NVARCHAR(20)) LIKE '%'+@Keyword+'%')";
            }
            return whereClause;
        }

        private string BuildOrderClause()
        {
            var orderClause = new StringBuilder();
            foreach (SearchSortItem sortItem in _criteria.SortItems)
            {
                if (sortItem.SortExpression == "TermName")
                {
                    orderClause.AppendFormat("t.TermName {0}", sortItem.SortOrder == SortOrder.Ascending ? "ASC" : "DESC");
                    orderClause.Append(',');
                }
                else
                {
                    orderClause.AppendFormat("e.{0} {1}", sortItem.SortExpression, sortItem.SortOrder == SortOrder.Ascending ? "ASC" : "DESC");
                    orderClause.Append(',');
                }
            }

            if (orderClause.Length <= 0)
            {
                orderClause.Append("e.CreateDate DESC");
            }
            else
            {
                orderClause.Remove(orderClause.Length - 1, 1);
            }
            return orderClause.ToString();
        }
    }
}
